import {
    View, Text, Dimensions, Image, TouchableOpacity, ScrollView, Alert, BackAndroid,
    DrawerLayoutAndroid, ImageBackground, StyleSheet, StatusBar, Platform, AsyncStorage,
    DeviceEventEmitter
} from 'react-native';
import React from 'react';
import LocalImg from '../const/Images'
import Urls, {getRealUrl} from '../const/Urls'
import MenuItem from '../component/MenuItem'
import MenuInfos from '../const/MeanInfos'
import {List, Button} from 'antd-mobile-rn'
import CodePush from "react-native-code-push";


let {width, height} = Dimensions.get("window");
if (Platform.OS === 'android') {
    height = height - StatusBar.currentHeight;
}

class Home extends React.Component {

    constructor(props) {
        super(props);

        this.navigation = this.props.navigation;
        this.state = {
            user: {
                token: '',
                pilotCode: '',
                pilotName: '',
                bmbm: '',
            },
            data: []
        }
    }


    componentDidMount() {
        this.setUser();
        this.loadData();
        CodePush.allowRestart();

        DeviceEventEmitter.addListener('login', () => {
            this.setUser();
        });
    }

    syncImmediate() {
        CodePush.sync({
                //安装模式
                //ON_NEXT_RESUME 下次恢复到前台时
                //ON_NEXT_RESTART 下一次重启时
                //IMMEDIATE 马上更新
                installMode: CodePush.InstallMode.IMMEDIATE,
                //对话框
                updateDialog: {
                    //是否显示更新描述
                    appendReleaseDescription: true,
                    //更新描述的前缀。 默认为"Description"
                    descriptionPrefix: "更新内容：",
                    //强制更新按钮文字，默认为continue
                    mandatoryContinueButtonLabel: "立即更新",
                    //强制更新时的信息. 默认为"An update is available that must be installed."
                    mandatoryUpdateMessage: "必须更新后才能使用！\n ",
                    //非强制更新时，按钮文字,默认为"ignore"
                    optionalIgnoreButtonLabel: '稍后',
                    //非强制更新时，确认按钮文字. 默认为"Install"
                    optionalInstallButtonLabel: '后台更新',
                    //非强制更新时，检查到更新的消息文本
                    optionalUpdateMessage: '有新版本了，是否更新？',
                    //Alert窗口的标题
                    title: '更新提示',
                    //deploymentKey为刚才生成的,打包哪个平台的App就使用哪个Key,这里用IOS的打包测试
                    deploymentKey: 'IjC3_iRGEZE8-9ikmBZ4ITJTz9wn6dec4087-57cf-4c9d-b0dc-ad38ce431e1d',
                },
            },
        );
    }

    componentWillMount() {
        CodePush.disallowRestart();//禁止重启
        this.syncImmediate(); //开始检查更新
    }


    loadData() {

        const request = new Map();
        request.set('pageNum', 1);
        fetch(getRealUrl(Urls['zyggUrl'], request), {
            method: "GET",
            headers: {
                Accept: "application/json",
                "Content-Type": "application/json"
            },
        })
            .then(response => response.json())
            .then(responseJson => {
                if (responseJson instanceof Array) {
                    this.setState({
                        data: responseJson,
                    });
                }
            })
            .catch(error => {
                console.error(error);
            });

    }

    navigate(screen) {
        this.navigation.navigate(screen);
    }

    setUser() {
        AsyncStorage.getItem("user", (error, result) => {
            if (!error) {

                const data = JSON.parse(result);
                if (data) {
                    this.setState({
                        user: {
                            token: data['token'],
                            pilotCode: data['pilotCode'],
                            pilotName: data['pilotName'],
                            bmbm: data['bmbm']
                        }
                    });
                } else {
                    this.setState({
                        user: {
                            token: '',
                            pilotCode: '',
                            pilotName: '',
                            bmbm: ''
                        }
                    });
                }
            }
        })
    }


    render() {
        const navigationView = (

            <View
                style={{
                    flexDirection: 'column',
                    height: height,
                    backgroundColor: '#ffffff'
                }}>

                <List renderHeader={() => '菜单'}>
                    <List.Item arrow="horizontal" multipleLine>
                        个人信息
                    </List.Item>

                    <List.Item arrow="horizontal" onClick={() => this.navigate('Setting')}>
                        应用设置
                    </List.Item>
                </List>

                <View style={{flex: 1}}/>

                <List>
                    <List.Item multipleLine
                               extra={<Button size='small' onClick={() => this.exitApp()}
                                              type='warning'>
                                   退出应用</Button>}>
                        台州港引航站
                        <List.Item.Brief>COPYRIGHT BY TAIZHOU PILOT,ALL RIGHTS RESERVED.</List.Item.Brief>
                    </List.Item>
                </List>
            </View>
        );

        return (
            <DrawerLayoutAndroid
                ref="drawer"
                drawerWidth={300}
                drawerPosition={DrawerLayoutAndroid.positions.Left}
                renderNavigationView={() => navigationView}>

                <ImageBackground style={{width: '100%', height: '100%', resizeMode: 'contain'}}
                                 source={LocalImg['background']}>
                    <View style={{flexDirection: 'column', alignItems: 'center'}}>

                        <View style={styles.titleView}>

                            <TouchableOpacity
                                onPress={() => this.refs.drawer.openDrawer()}>

                                <Image source={LocalImg['menu']}
                                       style={{width: 30, height: 30, marginLeft: 10, resizeMode: 'contain',}}
                                />
                            </TouchableOpacity>

                            <View style={styles.titleCenter}>
                                <Text style={styles.title}>台州港引航站</Text></View>
                            <View/>

                        </View>

                        <ImageBackground source={LocalImg['headview']}
                                         style={{
                                             width: width - 18,
                                             height: (height - 44) * 2 / 5,
                                             resizeMode: 'contain',
                                         }}>

                            <View style={styles.headerView}>

                                <View style={{
                                    width: width / 4, flexDirection: 'column',
                                    marginLeft: 10, justifyContent: 'center', alignItems: 'center'
                                }}>

                                    <TouchableOpacity style={styles.loginView} onPress={() => this.navigate('Login')}>
                                        <Image source={LocalImg['loginImg']}
                                               style={{height: height / 10, width: height / 10, resizeMode: 'contain'}}>
                                        </Image>
                                    </TouchableOpacity>

                                    <Text style={{height: 20, color: '#ffffff', fontWeight: 'bold'}}>
                                        {this.state.user.pilotName ? this.state.user.pilotName : '登录'}
                                    </Text>

                                </View>

                                <View style={{
                                    paddingTop: 20,
                                    justifyContent: 'flex-start',
                                    alignItems: 'center',
                                    flexDirection: 'column'
                                }}>
                                    <ScrollView>

                                        <Text style={{color: '#ffffff', marginRight: 10}}>
                                            通知 ：
                                        </Text>

                                        {this.newsView()}
                                    </ScrollView>
                                </View>


                            </View>


                            <View style={[styles.headerView, {paddingBottom: 40}]}>
                                <MenuItem navigation={this.props.navigation} key={'PageZygg'}
                                          page={'PageZygg'}
                                          img={LocalImg['icon_gkcsb']}
                                          title='重要公告'/>

                                <MenuItem navigation={this.props.navigation} key={'PageQxsj'}
                                          img={LocalImg['icon_qxsj']}
                                          page={'PageQxsj'}
                                          title='气象数据'/>

                                <MenuItem navigation={this.props.navigation} key={'PageCxsj'}
                                          img={LocalImg['icon_gcsj']}
                                          page={'PageCxsj'}
                                          title='潮汐数据'/>
                            </View>

                        </ImageBackground>

                        <ScrollView
                            showsVerticalScrollIndicator={true}
                            bounces={true}
                            style={{height: (height - 44) * 3 / 5}}
                            alwaysBounceVertical={true}>
                            <View style={{borderTopWidth: 1, flexDirection: 'column', borderColor: '#AAAAAA'}}>
                                <View style={styles.headerView}>
                                    {/*<TouchableOpacity style={styles.itemContainer}*/}
                                    {/*onPress={() => this.navigate('PageJkjh')}>*/}
                                    {/*<View>*/}
                                    {/*<Image style={styles.itemImage} source={LocalImg['icon_jkjh']}/>*/}
                                    {/*<Text style={styles.itemText}>进口计划</Text>*/}
                                    {/*</View>*/}
                                    {/*</TouchableOpacity>*/}

                                    {/*<TouchableOpacity style={styles.itemContainer}*/}
                                    {/*onPress={() => this.navigate('PageCkjh')}>*/}
                                    {/*<View>*/}
                                    {/*<Image style={styles.itemImage} source={LocalImg['icon_ckjh']}/>*/}
                                    {/*<Text style={styles.itemText}>出口计划</Text>*/}
                                    {/*</View>*/}
                                    {/*</TouchableOpacity>*/}

                                    {/*<TouchableOpacity style={styles.itemContainer}*/}
                                    {/*onPress={() => this.navigate('PageYbjh')}>*/}
                                    {/*<View>*/}
                                    {/*<Image style={styles.itemImage} source={LocalImg['icon_ybjh']}/>*/}
                                    {/*<Text style={styles.itemText}>移泊计划</Text>*/}
                                    {/*</View>*/}
                                    {/*</TouchableOpacity>*/}

                                    <TouchableOpacity style={styles.itemContainer}
                                                      onPress={() => this.navigate('PageAlljh')}>
                                        <View>
                                            <Image style={styles.itemImage} source={LocalImg['icon_jkjh']}/>
                                            <Text style={styles.itemText}>引航计划</Text>
                                        </View>
                                    </TouchableOpacity>

                                    <TouchableOpacity style={styles.itemContainer}
                                                      onPress={() => this.navigate('PageTlxx')}>
                                        <View>
                                            <Image style={styles.itemImage} source={LocalImg['icon_tlxx']}/>
                                            <Text style={styles.itemText}>拖轮信息</Text>
                                        </View>
                                    </TouchableOpacity>

                                    <TouchableOpacity style={styles.itemContainer}
                                                      onPress={() => this.navigate('PageMtbw')}>
                                        <View>
                                            <Image style={styles.itemImage} source={LocalImg['icon_llmtxx']}/>
                                            <Text style={styles.itemText}>码头泊位</Text>
                                        </View>
                                    </TouchableOpacity>

                                </View>


                                {/*<View style={styles.headerView}>*/}
                                {/*<TouchableOpacity style={styles.itemContainer}*/}
                                {/*onPress={() => this.navigate('PageZbqk')}>*/}
                                {/*<View>*/}
                                {/*<Image style={styles.itemImage} source={LocalImg['icon_dddbrz']}/>*/}
                                {/*<Text style={styles.itemText}>值班情况</Text>*/}
                                {/*</View>*/}
                                {/*</TouchableOpacity>*/}

                                {/*<TouchableOpacity style={styles.itemContainer}*/}
                                {/*onPress={() => this.navigate('PageMtbw')}>*/}
                                {/*<View>*/}
                                {/*<Image style={styles.itemImage} source={LocalImg['icon_llmtxx']}/>*/}
                                {/*<Text style={styles.itemText}>码头泊位</Text>*/}
                                {/*</View>*/}
                                {/*</TouchableOpacity>*/}

                                {/*<TouchableOpacity style={styles.itemContainer}*/}
                                {/*onPress={() => this.navigate('PageTlxx')}>*/}
                                {/*<View>*/}
                                {/*<Image style={styles.itemImage} source={LocalImg['icon_tlxx']}/>*/}
                                {/*<Text style={styles.itemText}>拖轮信息</Text>*/}
                                {/*</View>*/}
                                {/*</TouchableOpacity>*/}
                                {/*</View>*/}


                                {this.getMeanView()}

                            </View>
                        </ScrollView>

                    </View>


                </ImageBackground>

            </DrawerLayoutAndroid>
        )

    }


    getMeanView() {
        let results = [];
        if (this.state.user.token) {
            const emptyView = (<View style={styles.itemContainer}/>);

            for (let i = 0; i < MenuInfos.length; i = i + 3) {
                const first = MenuInfos[i];
                let second, third;
                if (i + 1 < MenuInfos.length) {
                    second = MenuInfos[i + 1];
                }

                if (i + 2 < MenuInfos.length) {
                    third = MenuInfos[i + 2];
                }

                results.push(<View style={styles.headerView} key={i}>
                    <TouchableOpacity style={styles.itemContainer}
                                      onPress={() => this.navigate(first.page)}>
                        <View>
                            <Image style={styles.itemImage} source={LocalImg[first.img]}/>
                            <Text style={styles.itemText}>{first.title}</Text>
                        </View>
                    </TouchableOpacity>
                    {second ?
                        <TouchableOpacity style={styles.itemContainer}
                                          onPress={() => this.navigate(second.page)}>
                            <View>
                                <Image style={styles.itemImage} source={LocalImg[second.img]}/>
                                <Text style={styles.itemText}>{second.title}</Text>
                            </View>
                        </TouchableOpacity>
                        :
                        emptyView
                    }
                    {
                        third ?
                            <TouchableOpacity style={styles.itemContainer}
                                              onPress={() => this.navigate(third.page)}>
                                <View>
                                    <Image style={styles.itemImage} source={LocalImg[third.img]}/>
                                    <Text style={styles.itemText}>{third.title}</Text>
                                </View>
                            </TouchableOpacity>
                            :
                            emptyView
                    }


                </View>)
            }
        }
        return results;
    }


    newsView() {

        let results = [];
        if (this.state.user.token) {
            for (let temp in this.state.data) {
                if (temp > 4)
                    break;
                results.push(<TouchableOpacity key={temp} onPress={() => this.navigate('PageZygg')}>
                    <View style={{paddingRight: 40, width: width * 3 / 4}}>
                        <Text style={{color: '#ffffff'}}>
                            {this.state.data[temp].VCTITLE}
                        </Text>
                    </View>
                </TouchableOpacity>)
            }
            return results;
        }
    }

    exitApp() {
        BackAndroid.exitApp()
    }


}

const styles = StyleSheet.create({
    title: {
        fontSize: 22,
        color: 'white'
    },
    titleCenter: {
        height: 42,
        width: '100%',
        position: 'absolute',
        alignItems: 'center',
        justifyContent: 'center',
    },
    titleView: {
        alignItems: 'center',
        width: '100%',
        height: 44,
        flexDirection: 'row'
    },
    itemContainer: {
        alignItems: 'center',
        flex: 1,
        height: width / 3,
        justifyContent: 'center'
    },
    itemImage: {
        width: 60,
        height: 60
    },
    itemText: {
        color: 'white'
    },
    headerView: {
        alignItems: 'flex-start',
        justifyContent: 'flex-start',
        width: width - 24,
        flexDirection: 'row',
        flex: 1
    },
    loginView: {
        marginTop: 20,
        width: width / 4,
        justifyContent: 'center',
        alignItems: 'center'
    },


});

export default Home;
